﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;

namespace YeaTrip.Comet
{
    /// <summary>
    /// Comet线程类，处理异步请求
    /// </summary>
    public class CometWaitThread
    {
        private const int CometDurationTime = 5;  // second

        private object state = new object();
        private List<CometAsyncResult> waitRequests = new List<CometAsyncResult>();

        //当前线程待处理请求列表
        public List<CometAsyncResult> WaitRequests
        {
            get { return this.waitRequests; }
        }

        //线程初始化是开始处理异步请求
        public CometWaitThread()
        {
            Thread t = new Thread(new ThreadStart(QueueCometWaitRequest_WaitCallback));
            t.IsBackground = false;
            t.Start();
        }

        internal void QueueCometWaitRequest(CometAsyncResult request)
        {
            lock (this.state)
            {
                waitRequests.Add(request);
            }

            // 更新座席状态
            //string agentID = GetAgentIDFromToken(request.clientID);
            //AgentStateManager.UpdateAgentState(agentID, request.agentState);
        }

        //将请求从待处理请求列表中移除
        internal void DequeueCometWaitRequest(CometAsyncResult request)
        {
            lock (state)
            {
                this.waitRequests.Remove(request);
            }

            // 更新座席状态
            //string agentID = GetAgentIDFromToken(request.clientID);
            //AgentStateManager.UpdateAgentState(agentID, request.agentState);
        }

        //响应请求后
        private void QueueCometWaitRequest_Finished(object target)
        {
            try
            {
                CometAsyncResult request = target as CometAsyncResult;
                request.SetCompleted();
            }
            catch { }
        }

        private void QueueCometWaitRequest_WaitCallback()
        {
            while (true)
            {
                try
                {
                    CometAsyncResult[] processRequest;

                    lock (this.state)
                    {
                        processRequest = waitRequests.ToArray();
                    }

                    for (int i = 0; i < processRequest.Length; i++)
                    {
                        PushMsg[] msgs = CheckForServerPushMsg(processRequest[i]);

                        // Comet超时或有消息，则返回
                        if (msgs != null || DateTime.Now.Subtract(processRequest[i].BeginTime).TotalSeconds >= CometDurationTime)
                        {
                            processRequest[i].ResponseObject = msgs;

                            //  queue the response on another ASP.NET Worker thread
                            this.QueueCometWaitRequest_Finished(processRequest[i]);

                            //  dequeue the request
                            DequeueCometWaitRequest(processRequest[i]);
                        }
                    }
                }
                catch { }

                Thread.Sleep(100);
            }
        }

        private PushMsg[] CheckForServerPushMsg(CometAsyncResult request)
        {
            //string agentID = GetAgentIDFromToken(request.clientID).ToUpper();
            ////string agentID = request.clientID.ToUpper().Trim();
            //return PushMsgQueue.GetAgentMsgs(agentID);            
            return null;
        }

    }
}
